package com.shuyuntu.proposal.controller;

import com.shuyuntu.proposal.entity.SystemConfig;
import com.shuyuntu.proposal.security.UseSecurity;
import com.shuyuntu.proposal.service.SystemConfigService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by limeng on 16/5/16.
 */
@Controller
@RequestMapping("/systemConfig")
public class SystemController {
    /**
     * 新建一次大会
     * @param config post来的大会信息
     *               {
     *                  endTime:xxx,
     *                  name:xxx
     *               }
     * @param session inject
     * @return jsonMap
     */
    @ResponseBody
    @RequestMapping(value = "/new", method = RequestMethod.POST)
    @UseSecurity(category = "0600")
    public Map<String, Object> newSystemConfig(
            @RequestBody Map<String, Object> config,
            HttpSession session) {
        Map<String, Object> resMap = new LinkedHashMap<>();
        SystemConfig latestConfig = systemConfigService.getLatestConfig();

        //如果当前大会的结束日期在现在之后,也就是当前大会尚未结束
        if (latestConfig != null && latestConfig.getEndTime().after(new Date())) {
            resMap.put("state", false);
            resMap.put("result", "当前大会尚未结束, 不能建立新的大会!");
        } else {    //其他情况
            if (configCheck(config)) {
                SystemConfig newConfig = new SystemConfig();
                newConfig.setTitle((String) config.get("title"));
                newConfig.setStartTime(new Date());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date endTime = sdf.parse((String)config.get("endTime"));
                    newConfig.setEndTime(endTime);
                } catch (Exception e) {
                    resMap.put("state", false);
                    resMap.put("result", "数据解析错误!");
                    return resMap;
                }

                boolean flag = systemConfigService.newSystemConfig(newConfig);
                if (flag) {
                    resMap.put("state", true);
                } else {
                    resMap.put("state", false);
                    resMap.put("result", "数据库错误!");
                }
            } else {
                resMap.put("state", false);
                resMap.put("result", "存在非法数据!");
            }
        }
        return resMap;
    }

    /*
     * 提供内部使用的状态检查函数
     */
    private boolean configCheck(Map<String, Object> config) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date endTime = sdf.parse((String)config.get("endTime"));
            //会议结束时间在今天之前
            if (endTime.before(new Date())) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取最近一次的大会配置设置
     * @return vo
     */
    @ResponseBody
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public SystemConfig getSystemSettingsVO() {
        SystemConfig vo = systemConfigService.getLatestConfig();
        return vo;
    }

    /**
     * 结束本次大会的附议
     *
     * @param session inject
     * @return jsonMap
     */
    @UseSecurity(category = "0600")
    @ResponseBody
    @RequestMapping(value = "/closeMotion", method = RequestMethod.POST)
    public Map<String, Object> closeMotion(HttpSession session) {
        Map<String, Object> resMap = new LinkedHashMap<>();
        int handleRes = systemConfigService.closeMotion();
        if (handleRes == 0) {
            resMap.put("state", true);
        } else if (handleRes == 1) {
            resMap.put("state", false);
            resMap.put("result", "大会已经结束了!");
        } else {
            resMap.put("state", false);
            resMap.put("result", "操作数据库时遇到问题!");
        }
        return resMap;
    }

    /**
     * 结束本次大会
     *
     * @param session inject
     * @return jsonMap
     */
    @ResponseBody
    @RequestMapping(value = "/close", method = RequestMethod.POST)
    @UseSecurity(category = "0600")
    public Map<String, Object> close(HttpSession session) {
        Map<String, Object> resMap = new LinkedHashMap<>();
        int handleRes = systemConfigService.close();
        switch (handleRes) {
            case 0:
                resMap.put("state", true);
                break;
            case 1:
                resMap.put("state", false);
                resMap.put("result", "大会已经结束了!");
                break;
            case 2:
                resMap.put("state", false);
                resMap.put("result", "操作数据库时遇到问题!");
                break;
            case 3:
                resMap.put("state", false);
                resMap.put("result", "附议仍在进行中!");
                break;
        }
        return resMap;
    }

    /**
     * 分页获取历史大会信息
     * @param pageSize 页长
     * @param pageNo 页码
     * @return map
     */
    @ResponseBody
    @RequestMapping(value = "/history/{pageSize}/{pageNo}", method = RequestMethod.GET)
    public Map<String, Object> queryHistoryWithPagination(
            @PathVariable int pageSize,
            @PathVariable int pageNo) {
        Map<String, Object> resMap = new LinkedHashMap<>();

        StringBuffer rowCount = new StringBuffer();
        try {
            List<SystemConfig> list =
                    systemConfigService.queryHistoryWithPagination(pageSize, pageNo, rowCount);

            resMap.put("state", true);
            resMap.put("list", list);
            Integer pageCount = (Integer.parseInt(rowCount.toString()) - 1) / pageSize + 1;
            resMap.put("pageCount", pageCount);

        } catch (Exception e) {
            e.printStackTrace();
            resMap.put("state", false);
            resMap.put("result", "数据库发生异常!");
        }

        return resMap;
    }

    /******* 依赖注入: *******/
    @Resource
    private SystemConfigService systemConfigService;

    public SystemConfigService getSystemConfigService() {
        return systemConfigService;
    }

    public void setSystemConfigService(SystemConfigService systemConfigService) {
        this.systemConfigService = systemConfigService;
    }
}
